﻿using Common;
using System;
using System.Windows;
using T68Control.Procdure;

namespace T68Control.ViewModel
{
    public class LoginViewModel : NotifyBase
    {
        public LoginModel LoginModel { get; set; } = new LoginModel();

        public CommandBase CloseWindowCommand { get; set; }

        public CommandBase LoginCommand { get; set; }

        private string _errorMessage = string.Empty;

        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { _errorMessage = value; this.DoNotify(); }
        }

        public LoginViewModel()
        {
            LoginModel.UserName = "";
            LoginModel.Password = "";

            this.CloseWindowCommand = new CommandBase();
            this.CloseWindowCommand.DoExecute = new Action<object>((o) =>
            {
                (o as Window).Close();
                if (!Global.IsLogin)
                {
                    System.Environment.Exit(0);
                }
            });

            this.LoginCommand = new CommandBase(DoLogin);
        }

        private bool logining = false;

        private void DoLogin(object o)
        {
            if (logining)
            {
                return;
            }
            logining = true;
            this.ErrorMessage = "";
            if (string.IsNullOrEmpty(LoginModel.UserName))
            {
                this.ErrorMessage = "用户名不能为空！";
                logining = false;

                return;
            }

            if (string.IsNullOrEmpty(LoginModel.Password))
            {
                this.ErrorMessage = "密码不能为空！";
                logining = false;
                return;
            }
            UserEntity user = UserHelper.GetInstance().CheckUserInfo(LoginModel.UserName, LoginModel.Password);
            if (user == null)
            {
                this.ErrorMessage = "登陆失败！用户名或密码错误";
                logining = false;
                return;
            }
            Global.User = user;
            Global.IsLogin = true;
            var win = o as Window;
            win.DialogResult = true;

            //if (Global.User.UserLevel == UserLevel.Admin)
            //{
            //    cbDebug.Visibility = Visibility.Visible;
            //    cbUserManager.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    cbDebug.Visibility = Visibility.Collapsed;
            //    cbUserManager.Visibility = Visibility.Collapsed;
            //}

            //win.Close();
        }
    }
}